package smb.web;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

/**
 * Servlet implementation class WebInterface
 */
@WebServlet(description = "web接口", urlPatterns = { "/interface" })
public class WebInterface extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SmbController c = new SmbController();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String action = request.getParameter("action");
		if (null == action) {
			writeData(response, AjaxData.Error(404, "action not found"));
		} else {
			try {
				Method m = c.getClass().getDeclaredMethod(action,new Class[] {HttpServletRequest.class,HttpServletResponse.class});
				Object obj = m.invoke(c, request,response);
				if(null != obj) {
					writeData(response, AjaxData.Success(obj));
				}
			} catch (NoSuchMethodException | SecurityException e) {
				writeData(response, AjaxData.Error(404, "action not found"));
			} catch (Exception e) {
				writeData(response, AjaxData.Error(500, e.getMessage()));
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private void writeData(HttpServletResponse res, Object data) throws IOException {
		String json = JSON.toJSONString(data);
		System.out.println(json);
		res.setContentType("application/json;charset=utf-8");
		res.getWriter().append(json);

	}

}
